﻿using CommonBase;
using CommonClass;
using EnvCommonUtility;
using SurveillanceLib;
using SurveillancePro.Base.Common;
using SurveillancePro.Base.ViewModels;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using ToolkitMgtModule.DataEnum;

namespace ToolkitMgtModule.Models
{
    /// <summary>
    /// 文件过滤
    /// </summary>
    public class FileFilterModel : ViewModelBase, IDataErrorInfo
    {
        #region Constructor

        public FileFilterModel()
        {
            try
            {
                _fillDriverTextsList(); // 加载 Combo_DriverTexts 下拉框
                _fillRecordFileTypesList(); // 加载 Combo_RecordFileTypes 下拉框

                _setDefaultDateTimeValue(); // 初始化日期值
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region Public Properties

        /// <summary>
        /// 设备树资源
        /// </summary>
        public ObservableCollection<ITreeGroup> Combo_DriverTexts { get; set; }

        private ITreeGroup _comboDriverText;
        /// <summary>
        /// 所选设备
        /// </summary>
        public ITreeGroup Combo_SearchDriverText
        {
            get
            {
                return _comboDriverText;
            }
            set
            {
                if (_comboDriverText == value) return;
                _comboDriverText = value;
                base.OnPropertyChanged("Combo_SearchDriverText");


                try
                {
                    _setDefaultDriverValue(); // 设备默认值
                }
                catch (System.Exception ex)
                {
#if DEBUG
                    Debug.WriteLine(ex.Message);
#endif
                }
            }
        }

        private ObservableCollection<ArgModel> _comboDriverChannels;
        /// <summary>
        /// 通道列表
        /// </summary>
        public ObservableCollection<ArgModel> Combo_DriverChannels
        {
            get
            {
                return _comboDriverChannels;
            }
            set
            {
                if (_comboDriverChannels == value) return;
                _comboDriverChannels = value;
                base.OnPropertyChanged("Combo_DriverChannels");
            }
        }

        private int _comboSearchDriverChannel;
        /// <summary>
        /// 通道号
        /// </summary>
        public int Combo_SearchDriverChannel
        {
            get
            {
                return _comboSearchDriverChannel;
            }
            set
            {
                if (_comboSearchDriverChannel == value) return;
                _comboSearchDriverChannel = value;
                base.OnPropertyChanged("Combo_SearchDriverChannel");
            }
        }

        /// <summary>
        /// 录像文件类型列表
        /// </summary>
        public List<ArgModel> Combo_RecordFileTypes { get; set; }

        /// <summary>
        /// 录像文件类型
        /// </summary>
        public int Combo_SearchRecordFileType { get; set; }

        /// <summary>
        /// 开始日期
        /// </summary>
        public DateTime? Date_SearchStartDate { get; set; }

        /// <summary>
        /// 结束日期
        /// </summary>
        public DateTime? Date_SearchEndDate { get; set; }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime? Time_SearchStartTime { get; set; }

        /// <summary>
        /// 结束时间
        /// </summary>
        public DateTime? Time_SearchEndTime { get; set; }

        #endregion

        #region Private Methods

        /// <summary>
        /// 填充设备树资源下拉值
        /// </summary>
        private void _fillDriverTextsList()
        {
            LoadDeviceTreeData();
        }

        /// <summary>
        /// 填充录像文件类型下拉值
        /// </summary>
        private void _fillRecordFileTypesList()
        {
            ArgModel argType;
            Combo_RecordFileTypes = new List<ArgModel>();

            // 填充 RecordFileTypeEnum 枚举
            foreach (RecordFileTypeEnum fileType in Utilities.GetEnumValues<RecordFileTypeEnum>())
            {
                argType = new ArgModel()
                {
                    iKey = (int)fileType,
                    sValue = Utilities.GetEnumDisplayDescription(fileType),
                };
                Combo_RecordFileTypes.Add(argType);
            }
        }

        /// <summary>
        /// 填充通道号下拉值
        /// </summary>
        /// <param name="channels">通道总数</param>
        private void _fillDriverChannelsList(int channels)
        {
            ArgModel argType;
            if (Combo_DriverChannels != null)
                Combo_DriverChannels.Clear();
            else
                Combo_DriverChannels = new ObservableCollection<ArgModel>();

            for (int i = 0; i < channels; i++)
            {
                argType = new ArgModel()
                {
                    iKey = i,
                    sValue = string.Format("通道{0}", i + 1),
                };
                Combo_DriverChannels.Add(argType);
            }

            Combo_SearchDriverChannel = 0; // 选择第一个通道号
            base.OnPropertyChanged("Combo_DriverChannels");
            base.OnPropertyChanged("Combo_SearchDriverChannel");
        }

        /// <summary>
        /// 处理日期初始值
        /// </summary>
        private void _setDefaultDateTimeValue()
        {
            Date_SearchStartDate = DateTime.Now.Date.AddDays(-1);
            Date_SearchEndDate = DateTime.Now.Date;

            Time_SearchEndTime = Time_SearchStartTime = DateTime.Now;
        }

        /// <summary>
        /// 设备默认值
        /// </summary>
        private void _setDefaultDriverValue()
        {
            if (Combo_SearchDriverText != null && Combo_SearchDriverText.Arg != null &&
                Combo_SearchDriverText.Arg is TagModel)
            {
                _fillDriverChannelsList((Combo_SearchDriverText.Arg as TagModel).Driver_ChannelCount);
            }
        }

        #endregion

        #region Public Methods

        /// <summary>
        /// 获取有效的设备（只加载登录成功的设备）
        /// </summary>
        public void LoadDeviceTreeData()
        {
            try
            {
                if (EnvUtilities.TreeViewSource == null || EnvUtilities.TreeViewSource.Count <= 0 ||
                    EnvUtilities.TreeViewSource.FirstOrDefault().Leaves == null ||
                    EnvUtilities.TreeViewSource.FirstOrDefault().Leaves.Count <= 0)
                {
                    Combo_DriverTexts = null;
                    Combo_SearchDriverText = null;
                    Combo_DriverChannels = null;
                    Combo_SearchDriverChannel = -1;

#if DEBUG
                    Debug.WriteLine("没有设备树资源");
#endif
                    System.Windows.MessageBox.Show("没有可用的设备资源", ConstantString.MSG_COMPANY);
                    return;
                }

                ObservableCollection<ITreeGroup> driverTextsList = 
                    EnvUtilities.TreeViewSource.FirstOrDefault().Leaves; // 去掉第一层的“添加设备”结点
                if (Combo_DriverTexts != null)
                    Combo_DriverTexts.Clear();

                Combo_DriverTexts = new ObservableCollection<ITreeGroup>(
                    driverTextsList.Where(p => p.Arg is TagModel && (p.Arg as TagModel).Driver_IsLogin)); // 得到只登录成功的设备列表
                base.OnPropertyChanged("Combo_DriverTexts");

                if (Combo_DriverTexts == null || Combo_DriverTexts.Count <= 0) // 没有可用的设备资源
                {
                    Combo_DriverChannels = null; // 通道列表为空
                    Combo_SearchDriverChannel = -1;
                }

                // 默认选择第一个设备
                if (Combo_DriverTexts != null && Combo_DriverTexts.Count > 0)
                {
                    Combo_SearchDriverText = Combo_DriverTexts.FirstOrDefault();
                }
            }
            catch (System.Exception ex)
            {
#if DEBUG
                Debug.WriteLine(ex.Message);
#endif
            }
        }

        #endregion

        #region IDataErrorInfo 成员

        public string Error { get; private set; }

        public string this[string columnName]
        {
            get
            {
                return this._getValidationError(columnName);
            }
        }

        #endregion

        #region Validation -- 默认验证全部值

        /// <summary>
        /// Returns true if this object has no validation errors.
        /// </summary>
        public int IsValid
        {
            get
            {
                int errorCount = 0;
                string errorInfo;

                foreach (string property in validatedProperties)
                {
                    errorInfo = _getValidationError(property);
                    if (!string.IsNullOrWhiteSpace(errorInfo))
                    {
                        Error = errorInfo; // 记录最后一个错误信息
                        errorCount += 1; // 记录错误个数
                    }
                }

                return errorCount;
            }
        }

        static readonly string[] validatedProperties = 
        {
            "Combo_DriverTexts",
            "Combo_SearchDriverText",
            "Combo_DriverChannels",
            "Combo_SearchDriverChannel",
            "Combo_RecordFileTypes",
            "Combo_SearchRecordFileType",
            "Date_SearchStartDate",
            "Date_SearchEndDate",
            "Time_SearchStartTime",
            "Time_SearchEndTime",
        };

        string _getValidationError(string propertyName)
        {
            if (Array.IndexOf(validatedProperties, propertyName) < 0)
                return null;

            string error = null; // 初值

            switch (propertyName)
            {
                case "Combo_DriverTexts":
                    error = this._validateDriverTexts();
                    break;
                case "Combo_SearchDriverText":
                    error = this._validateSearchDriverText();
                    break;
                case "Combo_DriverChannels":
                    error = this._validateDriverChannels();
                    break;
                case "Combo_SearchDriverChannel":
                    error = this._validateSearchDriverChannel();
                    break;
                case "Combo_RecordFileTypes":
                    error = this._validateRecordFileTypes();
                    break;
                case "Combo_SearchRecordFileType":
                    error = this._validateSearchRecordFileType();
                    break;
                case "Date_SearchStartDate":
                    error = this._validateSearchStartDate();
                    break;
                case "Date_SearchEndDate":
                    error = this._validateSearchEndDate();
                    break;
                case "Time_SearchStartTime":
                    error = this._validateSearchStartTime();
                    break;
                case "Time_SearchEndTime":
                    error = this._validateSearchEndTime();
                    break;



                default:
#if DEBUG
                    Debug.WriteLine(string.Format("异常：{0}", propertyName));
#endif
                    break;
            }

            return error;
        }

        string _validateDriverTexts()
        {
            if (Combo_DriverTexts == null ||
                Combo_DriverTexts.Count <= 0)
                return "没有设备资源信息";

            return null;
        }

        string _validateSearchDriverText()
        {
            if (Combo_SearchDriverText == null)
                return "请选择设备名称";

            return null;
        }

        string _validateDriverChannels()
        {
            if (Combo_DriverChannels == null ||
                Combo_DriverChannels.Count <= 0)
                return "没有通道列表信息";

            return null;
        }

        string _validateSearchDriverChannel()
        {
            if (Combo_SearchDriverChannel < 0)
                return "通道号异常";

            return null;
        }

        string _validateRecordFileTypes()
        {
            if (Combo_RecordFileTypes == null ||
                Combo_RecordFileTypes.Count <= 0)
                return "没有录像文件类型列表信息";

            return null;
        }

        string _validateSearchRecordFileType()
        {
            if (Combo_SearchRecordFileType < 0)
                return "录像文件类型异常";

            return null;
        }

        string _validateSearchStartDate()
        {
            if (Date_SearchStartDate == null)
                return "请输入开始日期";

            return null;
        }

        string _validateSearchEndDate()
        {
            if (Date_SearchEndDate == null)
                return "请输入结束日期";
            else if (Date_SearchStartDate.HasValue && Date_SearchEndDate.HasValue &&
                Date_SearchStartDate.Value > Date_SearchEndDate.Value)
                return "开始日期大于结束日期";
            else if (Date_SearchStartDate.HasValue && Date_SearchEndDate.HasValue &&
                Date_SearchStartDate.Value.AddMonths(1) < Date_SearchEndDate.Value)
                return "只能查询一个月内的数据";

            return null;
        }

        string _validateSearchStartTime()
        {
            if (Time_SearchStartTime == null)
                return "请输入开始时间";

            return null;
        }

        string _validateSearchEndTime()
        {
            if (Time_SearchEndTime == null)
                return "请输入结束时间";

            return null;
        }

        #endregion
    }
}
